<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/5/9 0009
 * Time: 14:55
 */

namespace app\general\model;


use app\common\model\Jpush;
use app\common\MoneyType;
use app\v2\model\SqMessageMoney;
use think\Exception;
use think\Model;

class SqRedPocket extends Model
{
    /*
     * 文章发布七天，若红包未领完，执行退款
     * aging_time  时效时长
     */
    public function timerArticleWithdrawal()
    {
        $where = [
            'srp.user_id' => 0,
            'srp.is_withdrawal' => 0,
        ];

        //文章用户相关信息
        $art_info = $this->alias('srp')
            ->field('srp.art_id,sum(srp.money) as money,sa.sq_jinzhu_id,sa.title,sq.current_money, sq.used_money,sq.device_id')
            ->join('xys_sq_article sa', 'sa.id=srp.art_id')
            ->join('xys_sq_jinzhu sq', 'sq.id=sa.sq_jinzhu_id')
            ->where($where)
            ->whereTime('srp.create_time', 'between', ['-8 days', '-7 days'])
            ->group('srp.art_id')
            ->select();
        if(empty($art_info)) return 'nothing to do';

        $record = [];   //资金流水表记录数据
        $log=[];//消息日志记录数据
        $sq_jinzhu_ids = [];  //金主ids
        $sq_jinzhu_info = [];  //金主信息
        $sq_jinzhu_notice = []; //金主消息
        $sq_jinzhu_key = 0;
        $time = time();
        foreach ($art_info as $key=>$value){
            if(!in_array($value['sq_jinzhu_id'], $sq_jinzhu_ids)){
                array_push($sq_jinzhu_ids, $value['sq_jinzhu_id']);
                $sq_jinzhu_info[$sq_jinzhu_key] = [
                    'id' => $value['sq_jinzhu_id'],
                    'current_money' => $value['current_money'],
                    'used_money' => $value['used_money'],
                ];
                $sq_jinzhu_key++;
            }

            //资金流水表记录数据
            $record[$key] = [
                'trade_no' => get_trade(),
                'sq_jinzhu_id' => $value['sq_jinzhu_id'],
                'money' => $value['money'],
                'type' => MoneyType::REFUDE_ARTICLE_ENVELOPE,  //广告时效退款
                'create_time' => $time,
                'is_add' => 1,
                'status' => 1,
                'sq_article_id' => $value['art_id']
            ];
            $log[$key]=[
                'sq_jinzhu_id' => $value['sq_jinzhu_id'],
                'money' => $value['money'],
                'genre'=>MoneyType::REFUDE_ARTICLE_ENVELOPE,
                'status'=>'已退还到余额',
                'source'=>$value['title'],
                'time'=>time()
            ];

            //金主消息
            $sq_jinzhu_notice[$key] = [
                'sq_jinzhu_id' => $value['sq_jinzhu_id'],
                'type' => 5,   //文章红包时效退款
                'content' => '您的文章《'.$value['title'].'》有未领完红包，超过7天时效，退还剩余红包金额'.$value['money'].'元，请到账户余额中查看',
                'create_time' => $time,
                'extras' => json_encode(['type'=>5, 'art_id' => $value['art_id']]),
                'device_id' => $value['device_id']
            ];
        }

        $update_jinzhu = [];
        foreach ($sq_jinzhu_info as $key=>$value){
            foreach ($art_info as $k=>$v){
                if($v['sq_jinzhu_id'] == $value['id']){
                    $value['current_money'] += $v['money'];
                    $value['used_money'] -= $v['money'];
                }
            }
            $update_jinzhu[$key] = $value;
        }

        $this->startTrans();
        try{
            //1.改变红包记录表的is_withdrawal
            if(!$this->alias('srp')->where($where)->whereTime('srp.create_time', 'between', ['-8 days', '-7 days'])->setField('srp.is_withdrawal',1)) error('红包记录1失败');

            //2.存入资金流水记录表
            if(!(new SqMoney())->saveAll($record)) error('资金记录2失败');

            //3.更新金主表
            if(!(new SqJinzhu())->saveAll($update_jinzhu)) error('金主表3失败');

            //4.插入消息表
            if(!(new SqNotice())->allowField(true)->saveAll($sq_jinzhu_notice)) error('消息表4失败');
            //5.存入消息表
            (new SqMessageMoney())->saveAll($log);
            $this->commit();
        }catch(Exception $exception){
            $this->rollback();
            $exception->getMessage();
        }

        $jpush = new Jpush();
        for($i=0; $i<count($sq_jinzhu_notice); $i++){
            if($sq_jinzhu_notice[$i]['device_id']) $jpush->push($sq_jinzhu_notice[$i]);
        }
        return 'success';
    }

}